package cn.edkuir.ware.listener;

import cn.edkuir.common.to.mq.StockDetailTo;
import cn.edkuir.common.to.mq.StockLockedTo;
import cn.edkuir.common.utils.R;
import cn.edkuir.ware.entity.WareOrderTaskDetailEntity;
import cn.edkuir.ware.entity.WareOrderTaskEntity;
import cn.edkuir.ware.service.WareSkuService;
import cn.edkuir.ware.vo.OrderVo;
import com.alibaba.fastjson.TypeReference;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Autowired
    private WareSkuService wareSkuService;


    /**
     * 库存自动解锁
     * 2) 下单成功、库存锁定成功, 但接下来的业务调用失败, 订单回滚
     *
     * 解锁库存失败, 一定要告诉服务解锁失败
     */
    @RabbitHandler
    public void handleStockRelease(StockLockedTo stockLockedTo, Message message, Channel channel) throws IOException {
        try {
            wareSkuService.unlock(stockLockedTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

}
